import {ArrayList} from './ArrayList';

export function JSONObject(){
    this.obj = {};

    this.put = function(k,v){
        eval("this.obj." + k + "='" + v + "'");
    };

    this.opt = function(k){
        return eval("this.obj." + k);
    };

    this.optString = function(k){
        return this.opt(k);
    };

    this.optInt = function(k,def){
        var val = def || 0;
        try{
            var res = parseInt(eval("this.obj." + k),10);
            if(isNaN(res))
                return val;
            return res;
        }catch(E){}
        return val;
    };

    this.optFloat = function(k,def){
        var val = def || 0;
        try{
            var res = parseFloat(eval("this.obj." + k));
            if(isNaN(res))
                return val;
            return res;
        }catch(E){}
        return val;
    };

    this.get = function(k){
        return this.opt(k);
    };

    this.toJsonObject = function(){
        return this.obj;
    };

    this.toString = function(){
        return JSON.stringify(this.obj);
    };

    this.parse = function(json){
        if(typeof json === 'object'){
            this.obj = json;
            return this;
        }

        this.obj = eval("(" + json + ")");
        return this;
    };

    this.isEmpty = function(){
        return 0 === this.keys().length;
    };

    this.keys = function(){
        var o = this.obj;
        var arr = [];
        for(var i in o){
            arr.push(i);
        }
        return arr;
    };
}


export function JSONArray(){
    this.list = new ArrayList();

    this.put = function(v){
        this.list.add(v);
    };

    this.has = function(v){
        return this.list.contains(v);
    };

    this.length = function(){
        return this.list.size();
    };

    this.opt = function(index){
        return this.list.get(index);
    };

    this.get = function(index){
        return this.opt(index);
    };
    this.toString = function(){
        return JSON.stringify(this.list.arr);
    };
    this.parse = function(jsonArr){
        if(jsonArr instanceof ArrayList)
            this.list = jsonArr;
        else
            this.list.arr = JSON.parse(jsonArr + "");
        return this;
    };
    this.asList = function(){
        return this.list;
    };

    this.isEmpty = function(){
        return this.length === 0;
    };
}